import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.PublishSubject
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.io.File
import java.io.FileFilter
import javax.swing.*

class ClearUnusedPictures : JPanel() {
    private val path = BehaviorSubject.createDefault("C:\\Users\\bing\\note")
    private var message: String = ""
    private val deleteFlag = BehaviorSubject.createDefault(false)
    private val finishFlag = PublishSubject.create<Boolean>()

    private val chooseBtn: JButton
    private val startBtn: JButton
    private val logText: JTextArea
    private val layout = GridBagLayout()
    private val deleteBox: JCheckBox

    init {
        setLayout(layout)
        chooseBtn = JButton("选择文件夹").also {
            layout.setConstraints(it, gbc(0, 0, 1, 1) { weightx = 1.0 })
            it.addActionListener {
                val chooser = JFileChooser()
                chooser.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
                chooser.showDialog(JLabel(), "选择")
                path.onNext(chooser.selectedFile.absolutePath)
            }
            add(it)
        }
        logText = JTextArea("请选择目录").also {
            layout.setConstraints(it, gbc(0, 1, 3, 1) {
                fill = GridBagConstraints.BOTH
                weighty = 1.0
            })
            add(it)
        }
        startBtn = JButton("开始清理").also {
            layout.setConstraints(it, gbc(1, 0, 1, 1) { weightx = 1.0 })
            add(it)
            it.addActionListener {
                clear(this.path.value)
                finishFlag.onNext(true)
            }
        }
        deleteBox = this.addWithConstraints(JCheckBox("删除图片？"), gbc(2, 0, 1, 1) { weightx = 1.0 }) {
            addActionListener {
                deleteFlag.onNext(this.isSelected)
            }
        }

        path.subscribe { text ->
            clearLog()
            this.logText.text = text
        }
        finishFlag.subscribe { this.logText.text = this.message }
    }

    private fun log(message: String) {
        this.message += ("\n" + message)
    }

    private fun clearLog() {
        this.message = ""
    }

    private fun clear(path: String) {
        log("输入目录：$path")
        val regex = """!\[.*\]\(res/(.*.png)\)""".toRegex()
        File(path).doWithMd {
            val mdPics = regex.findAll(readText()).map { it.groupValues[0] }.toList()
            if (mdPics.isEmpty()) return@doWithMd
            val resDir = File(parentFile, "res").apply { if (!exists()) return@doWithMd }
            val resPics = resDir.listFiles(FileFilter { it.extension == "png" })!!.map { it.name }
            resPics.filter { it !in mdPics }.forEach {
                val pic = File(resDir, it)
                log("找到无用图片：${pic.absolutePath}")
                if (deleteFlag.value) {
                    log("删除图片：${pic.absolutePath}")
                    pic.delete()
                }
            }
        }
    }

    fun <T : JComponent> JComponent.addWithConstraints(child: T, constraints: GridBagConstraints, init: T.() -> Unit): T {
        (this.layout as GridBagLayout).setConstraints(child, constraints)
        add(child)
        child.init()
        return child
    }
}

